package com.wcgksoft.controller.admin;

import com.wcgksoft.common.util.Layui;
import com.wcgksoft.entity.order.Order;
import com.wcgksoft.service.order.OrderService;
import net.sf.json.JSONObject;
import org.beetl.ext.fn.Json;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author 御风
 * @version V1.0
 * @Package com.wcgksoft.controller
 * @Description TODO
 * @date 2020/5/16 17:23
 * @ClassName AdminOrderController
 */
@Controller
@RequestMapping("adminOrder")
public class AdminOrderController {

    @Autowired
    private OrderService orderService;

    @ResponseBody
    @RequestMapping(value = "findAll")
    public Layui findAll(@RequestParam(value = "page", required = false) Integer page,
                         @RequestParam(value = "limit", required = false) Integer limit) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Order.class);
        criteria.addOrder(org.hibernate.criterion.Order.desc("buyTime"));
        List<Order> list = orderService.findByConditions(criteria, page, limit);
        return Layui.data(0, "success", orderService.getTotalCount(), list);
    }

    @ResponseBody
    @RequestMapping(value = "saveOrder")
    public Layui save(@RequestParam(value = "data",required = false)String data){
        JSONObject param = JSONObject.fromObject(data);
        Order order=null;
        if (null==param){
            return Layui.data(1, "请求格式有误", 0, null);
        }else{
            String orderIdByTime = getOrderIdByTime();
            order.setOrderNo(orderIdByTime);
            order.setBuyTime(new Date());
            return Layui.data(0,"success",1,Layui.addList(order));
        }
    }


    /**
     * 生成订单号
     * @return
     */
    public static String getOrderIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }
}
